<?php

 class Authenticate
{
    const AUTH_SUCCESS = 1; 
    const AUTH_PASSWORD_FAILED = 2;
    const AUTH_USER_NOT_FOUND = 3;
    
    const AUTH_SESSION_USER = 'UserIdentity';
    
    /**
     * Action preDispatch
     * @param Route $route
     * @return Route
     */
    public function preDispatch($route)
    {
        $checkAuth = true;
        $listAllowUrl = Route::AllowUrls();
        foreach($listAllowUrl as $item)
        {
            if ($route->controller == $item->controller && $route->action == $item->action )
                $checkAuth = false;
        }
        
        if ($checkAuth)
        {
            if (!self::verifyIfUserAuthenticate()){
                Application::redirectPage('Index','Login');
            }
            else{
                return $route;
            }
        }
        else{   
            return $route;            
        }
    }
    
    /**
     * @return UserIdentity
     */
    public static function UserIdentity()
    {        
        return (isset($_SESSION[self::AUTH_SESSION_USER]))? unserialize($_SESSION[self::AUTH_SESSION_USER]):NULL;
    }
    
    /**
     * @return bool
     */
    public static function verifyIfUserAuthenticate()
    {
        return (isset($_SESSION[self::AUTH_SESSION_USER]));
    }
    
    /**
     * Metodo Autenticador Generico
     * @param string $autenticatorType
     * @param string $username
     * @param string $password
     * @return type AuthResult
     */
    public static function auth($autenticatorType,$username,$password)
    {
        $class = 'UserAuth' . ucfirst($autenticatorType);
        $objAuth = new $class($username,$password);
        $authResult = $objAuth->authenticate();
        if ( $authResult == self::AUTH_SUCCESS)
        {
            $_SESSION[self::AUTH_SESSION_USER] = serialize($objAuth->getUser());
        }
        return $authResult;
    }
    
    public static function logout()
    {
        $_SESSION[self::AUTH_SESSION_USER] = null;
    }
}

